﻿using System;
using System.Collections.Generic;

namespace ETModel {
    /// <summary>
    /// 配置加载只需要Model层的即可,热更和model层是一起加载的
    /// </summary>
    [ObjectSystem]
    public class ConfigAwakeSystem : AwakeSystem<ConfigComponent, string> {
        public override void Awake(ConfigComponent self, string configDir) {
            self.Awake(configDir);
        }
    }

    //服务端不需要类型一加载就初始化,等调用者加载组件时(awake),传入配置目录再初始化
    //[ObjectSystem]
    //public class ConfigLoadSystem : LoadSystem<ConfigComponent> {
    //    public override void Load(ConfigComponent self) {
    //        self.Load();
    //    }
    //}

    /// <summary>
    /// 服务端model层配置组件拓展(服务端的配置走model层即可)
    /// </summary>
    public static class ConfigComponentHelper {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="self"></param>
        /// <param name="configDir">配置文件所在目录(相对服务器运行目录)</param>
        public static void Awake(this ConfigComponent self, string configDir) {
            AppType appType = StartConfigComponent.Instance.StartConfig.AppType;

            self.AllConfig.Clear();
            List<Type> types = Game.EventSystem.GetTypes(typeof(ConfigAttribute));

            foreach (Type type in types) {
                object[] attrs = type.GetCustomAttributes(typeof(ConfigAttribute), false);
                if (attrs.Length == 0) {
                    continue;
                }

                ConfigAttribute configAttribute = attrs[0] as ConfigAttribute;
                // 只加载指定的配置
                if (!configAttribute.Type.Is(appType)) {
                    continue;
                }

                object obj = Activator.CreateInstance(type);

                ACategory iCategory = obj as ACategory;
                if (iCategory == null) {
                    throw new Exception($"class: {type.Name} not inherit from ACategory");
                }
                //服务器直接存放配置文件所在目录(相对服务器运行目录)
                iCategory.ConfigFileInfo = configDir;
                iCategory.BeginInit();
                iCategory.EndInit();

                self.AllConfig[iCategory.ConfigType] = iCategory;
            }
        }

    }
}
